import { initLang, Vue, store, router, i18n } from '@/utils/commonJs/initLang.js'
import { ElementUI } from '@/utils/commonJs/initElement.js'
let limitRouter = ['call', 'webchat', 'email', 'customer', 'business']
let firstIn = true
let secondIn = false // 解决刷新页面login执行两次的问题
import * as m7Utils from '@/utils/m7Utils'
import NodeRSA from 'node-rsa'
import loginApi from '@/store/api/login'

// 加载设置模块的语音包
// let count = 0
// function featchI18n () {
//   let langTemp = window.localStorage.getItem('lang') || 'zh_CN'
//   let url = window.location.origin + '/static/i18n/locales/' + langTemp + '_Config' + '.json'
//   let currentLocales = i18n.getLocaleMessage(langTemp || 'zh_CN')
//   window.fetch(url + '?_=' + Math.random(), {
//     method: 'get',
//     headers: {
//       'Content-Type': 'application/json'
//     }
//   })
//   .then(response => response.json())
//   .then((res) => {
//     let locales = ''
//     switch (langTemp) {
//       case 'zh_CN':
//         locales = {...res, ...currentLocales}
//         break
//       case 'zh_TW':
//         locales = {...res, ...currentLocales}
//         break
//       case 'en':
//         locales = {...res, ...currentLocales}
//         break
//       default:
//         locales = {...res, ...currentLocales}
//         break
//     }
//     i18n.setLocaleMessage(langTemp || 'zh_CN', locales)
//     window.langJson = locales || {}
//     store.commit('LOAD_LOCAL_FLAG', true)
//   }).catch((res) => {
//     store.commit('LOAD_LOCAL_FLAG', false)
//     if (count < 3) {
//       featchI18n(langTemp, this.count++)
//     } else {
//       window.alert('Network anomaly！！！ Please check your network')
//     }
//   })
// }

router.beforeEach((to, from, next) => {
  let ss = window.sessionStorage
  let locales = {}
  // 由邮箱验证 和 手机验证刷新页面 调回登录
  let data = { localTime: new Date().getTime(), domain: window.location.href.split('/')[2] }
  if (window.parent !== window && firstIn) {
    try {
      // 判断同源，同源则跳到登陆页面，try防止报错
      if (window.parent.location.origin === window.location.origin) {
        firstIn = false
        next({ path: '/login' })
      }
    } catch (e) {
    }
  }
  if (from.path === '/' && to.path !== '/login' && !secondIn && !store.state.login) {
    if (window.sessionStorage.loginType !== 'token' && window.sessionStorage.loginType !== 'sessionId') {
      let clientMenu = store.state.session.clientMenu || []
      let arr1 = to.path.split('/')
      let isAllow = true
      for (let k = 0; k < clientMenu.length; k++) {
        if (clientMenu[k].id === 'nav_' + arr1[2]) {
          isAllow = false
          break
        }
      }
      if (isAllow && !window.sessionStorage.loginData) {
        ElementUI.Message.error('您没有该模块权限，无法跳转！')
        next({path: '/login'})
        return
      }
    }
    store.commit('getNavMenuState') // 从sessionStoreage获取导航的展开收起状态
    if (ss.loginData || ss.loginType) {
      store.dispatch('initSystemConfig', data)
        .then(() => {
        }).then(async () => {
          initLang()
          let loginType = null
          if (window.sessionStorage.loginType === 'sessionId') {
            // sessionId登录
            loginType = store.dispatch('signInBysessionId', { sessionId: window.sessionStorage.sessionId })
          } else if (window.sessionStorage.loginType === 'token') {
            // token登录
            loginType = store.dispatch('signInByToken', { token: window.sessionStorage.loginToken })
            // token登录后走普通刷新
            window.sessionStorage.removeItem('loginType')
          } else {
            // 普通刷新
            if (window.sessionStorage.getItem('emailCheck') === 'true' || window.sessionStorage.getItem('ipCheck') === 'true') {
              next({ path: '/login' })
              if (window.langJson) {
                ElementUI.Message.error(window.langJson.message.safatyed)
              }
              return
            } else {
              let defaultLogin = ''
              if (window.sessionStorage.loginData) {
                defaultLogin = JSON.parse(window.sessionStorage.loginData)
              }
              const res1 = await loginApi.getLoginSecretKey({})
              if (res1.success) {
                let key = new NodeRSA(res1.secret)
                let _form = m7Utils.deepClone(defaultLogin)
                // base64
                let encrypted = key.encrypt(_form.password + ':' + res1.num, 'base64')
                _form.safeKey = encrypted
                let isCaptcha = store.state.isCaptcha
                if (isCaptcha) {
                  let loginToken = window.sessionStorage.getItem('loginToken')
                  _form.loginToken = loginToken
                }
                loginType = store.dispatch('signIn', _form)
              }
            }
          }
          loginType
            .then((data) => {
              // 刷新只到列表
              if (!data || !data.success) {
                next({ path: '/login' })
                return
              }
              locales = window.langJson || {}
              Vue.set(Vue.config, 'lang', window.localStorage.lang || 'zh_CN')
              // Vue.locale(window.localStorage.lang || 'zh_CN', locales)
              i18n.setLocaleMessage(window.localStorage.lang || 'zh_CN', locales)
              i18n.locale = window.localStorage.lang
              let moduleArr = to.path.split('/')
              // featchI18n()
              if (limitRouter.indexOf(moduleArr[2] !== -1) && moduleArr.length > 3) {
                router.afterEach((route) => {
                  let title = route.meta.title || ''
                  console.warn(store)
                  if (locales.routeI18n && locales.login) { // 解决偶发window语言包没有取到的情况，初步判断是异步导致的，暂无法复现，先做下报错兼容
                    document.title = `${locales.routeI18n[title] || title} - ${locales.login.cloudService}${store.getters.accountName}`
                  }
                })
                secondIn = true
                if (moduleArr[2] === 'call') {
                  next({ path: '/index/' + moduleArr[2] + '/cdr_call' })
                } else if (moduleArr[2] === 'webchat') {
                  next({ path: '/index/' + moduleArr[2] + '/webchat_todo' })
                } else {
                  next({ path: '/index/' + moduleArr[2] })
                }
              } else {
                next()
              }
            }).catch(() => {
              next('/login')
            })
        })
    } else {
      next('/login')
    }
  } else {
    if (to.path === '/login') {
      store.dispatch('initSystemConfig', data).then(() => {
        next()
      }).catch(() => {
        store.commit('INIT_CONFIG', { data: { oemFlag: 'error' } })
        next()
      })
    } else {
      next()
    }
  }
})
export { initLang, Vue, store, router, i18n, ElementUI }
